/**
 * 游戏管理类
 */

import superManager from "./superManager";
import gameMode_json, { GAME_MODE, SCENE_MODE } from "./gameContent/gameMode_json";
import O1HD, { managers, modules } from "../gameEngine";
import data_control from "../libs/data_control";
import gameConfig from "../configs/gameConfig";
import versionNotice from "../../O1ModuleRes/frame/versionNotice";


export interface GameModeDetail {
    type: GAME_MODE;
    name: string;
    sceneName: string;
    sceneMode: SCENE_MODE;
    explain: string;
    //看视频解锁次数
    lookVideCount: number;
    //是否为主场景 主场景会替换hall场景为loading后载入 必须为场景 不能为预制体
    isMainScene?: boolean;
    //已看视频次数
    currLookedVideoCount?: number;
    //看视频日期
    lookVideoUnlockDate?: string;
    //
    bundle?: cc.AssetManager.Bundle;
    //
    currScenePrefabNode?: cc.Node;
}

export default class GameManager extends superManager {
    //
    className: string = '游戏管理';
    //
    private m_currGameMode: GameModeDetail = null;
    //游戏公告
    private m_versionNotice: string = null;
    //游戏公告KEY
    private readonly m_VERSION_NOTICE_KEY: string = 'game-version-notice';


    constructor() {
        super();
    }

    async loadManager(): Promise<void> {
        await super.loadManager();
        //
        this.m_versionNotice = O1HD.getServices().localStorageSrv.getStorage(this.m_VERSION_NOTICE_KEY);
        return Promise.resolve();
    }

    //游戏首次进入
    onGameRun() {
        //
        let currVersion = gameConfig.VERSION_NOTICE;
        //
        if (this.m_versionNotice != currVersion) {
            //
            this.m_versionNotice = currVersion;
            O1HD.getServices().localStorageSrv.setStorage(this.m_VERSION_NOTICE_KEY, this.m_versionNotice);
            //
            this.showVersionNotice();
        }
        const tt = window['tt'];
        if (tt) {
            let options = tt.getLaunchOptionsSync();
            console.log(options.showFrom);
            console.log('启动参数', options, JSON.stringify(options));
        }
    }

    showVersionNotice() {
        if (this.m_versionNotice) {
            modules().uiControlModule.showFramePrefab('preload/frame/versionNotice', null, false, node => {
                node.getComponent(versionNotice).setNotice(this.m_versionNotice);
            });
        }
        // this.m_versionNotice && O1HD.getModules().uiControlModule.showDialogBox('版本公告', this.m_versionNotice);
    }

    getVersionNotice() {
        return this.m_versionNotice;
    }

    async loadModeOver(isShowLoading:boolean = true) {
        console.log('加载子游戏场景', this.m_currGameMode.sceneName);
        if(isShowLoading){
            await O1HD.getModules().uiControlModule.showLoading();
        }
        //
        switch (this.m_currGameMode.sceneMode) {
            case SCENE_MODE.FIRE: {
                await new Promise<void>((resolve, reject) => {
                    O1HD.loadScene(this.m_currGameMode.sceneName, () => {
                        resolve();
                        // O1HD.getModules().uiControlModule.hideLoading();
                    });
                });
                break;
            }
            case SCENE_MODE.PREFAB: {
                this.m_currGameMode.bundle.load(this.m_currGameMode.sceneName, cc.Prefab, (error, assets: cc.Prefab) => {
                    if (error) {
                        console.error('#55 模式对应预制体不存在或异常', this.m_currGameMode);
                        return;
                    }
                    this.m_currGameMode.currScenePrefabNode = cc.instantiate(assets);
                    O1HD.Canvas().addChild(this.m_currGameMode.currScenePrefabNode);
                    O1HD.getModules().uiControlModule.hideLoading();
                });
                break;
            }
            default: {
                O1HD.getModules().uiControlModule.hideLoading();
                console.error('#56 请指示加载模式的类型');
                break;
            }
        }
    }

    //获取主场景名
    getMainSceneNameAndLoadBundle(): string | GameModeDetail {
        //
        //
        // for (let mode of gameMode_json()) {
        //     if (mode.isMainScene) {
        //         //是场景
        //         if (mode.sceneMode == SCENE_MODE.FIRE) {
        //             this.m_currGameMode = mode;
        //             //加载子包
        //             return mode;
        //         } else {
        //             console.error('入口场景模式不允许为预制体', mode.name, mode);
        //             return null;
        //         }
        //     }
        // }
        return 'hall';
    }

    setMainModeLoaded(mode: GameModeDetail) {
        this.m_currGameMode = mode;
    }

    //选择模式
    async selectMode(mode: GAME_MODE,isShowLoading:boolean) {
        //
        let currMode: GameModeDetail = null;
        //
        currMode = gameMode_json()[mode];
        if (currMode == null) {
            O1HD.getModules().uiControlModule.showMessageBox(`敬请期待${mode}`);
            return;
        }
        this.m_currGameMode = currMode;
        //
        //在其他地方已经加载子包
        if (currMode.bundle == null) {
            console.debug('子包是否已加载', currMode.name, cc.assetManager.bundles.get(currMode.name) != null);
            let bundle = cc.assetManager.bundles.get(currMode.name);
            if (bundle) {
                currMode.bundle = bundle;
            }
        }
        if (currMode.bundle == null) {
            console.log('显示进度');
            // O1HD.getModules().uiControlModule.showLoading();
            console.log('进度显示完', currMode, mode);
            await new Promise<void>((resolve, reject) => {
                cc.assetManager.loadBundle(currMode.name, async (err, bundle: cc.AssetManager.Bundle) => {
                    // O1HD.getModules().uiControlModule.hideLoading();
                    if (err) {
                        console.error('游戏子包不存在', mode);
                        return;
                    }
                    currMode.bundle = bundle;
                    managers().soundMgr.addOneSoundBundle(currMode.name,bundle);
                    await this.loadModeOver(isShowLoading);
                    resolve();
                });
            });
        } else {
            //
            await this.loadModeOver(isShowLoading);
        }
    }



    getCurrMode() {
        return this.m_currGameMode;
    }

    getCurrModeNeedPower() {
        let { type } = this.m_currGameMode;
        return this.getModeNeedPower(type);
    }

    getModeNeedPower(mode: GAME_MODE) {
        //TODO:获取对应体力 对照oss根据type映射
        return 0;
    }

    getModeInfo(mode: GAME_MODE) {
        let md = gameMode_json()[mode];
        if (md && md.lookVideCount > 0) {
            md.currLookedVideoCount =
                Number(O1HD.getServices().localStorageSrv.getStorage(`mode-looked-${md.type}`) || '');
            md.lookVideoUnlockDate =
                O1HD.getServices().localStorageSrv.getStorage(`mode-looked-date-${md.type}`) || '';
            //
        }
        return md;
    }

    addModeLookCount(mode: GAME_MODE) {
        let md = gameMode_json()[mode];
        if (md.lookVideCount > 0) {
            md.currLookedVideoCount++;
            O1HD.getServices().localStorageSrv.setStorage(`mode-looked-${md.type}`, md.currLookedVideoCount);
            O1HD.getServices().localStorageSrv.setStorage(`mode-looked-date-${md.type}`, data_control.getCurrDateDayString());
        }
    }

    //返回大厅
    async returnMainScene() {
        await O1HD.getModules().uiControlModule.showLoading();
        //
        switch (this.m_currGameMode.sceneMode) {
            case SCENE_MODE.PREFAB: {
                if (this.m_currGameMode.currScenePrefabNode && this.m_currGameMode.currScenePrefabNode.isValid) {
                    this.m_currGameMode.currScenePrefabNode.destroy();
                }
                this.m_currGameMode.currScenePrefabNode = null;
                //
                O1HD.getModules().uiControlModule.hideLoading();
                break;
            }
            case SCENE_MODE.FIRE: {
                //
                await new Promise<void>((resolve, reject) => {
                    O1HD.loadScene('loading', resolve);
                });
                O1HD.getModules().uiControlModule.hideLoading();
                break;
            }
        }
    }
}